import { Table } from "../domain/model/table";
import { Store } from '../domain/model/store';
import { DataContextFactory } from '../domain/fbsDataContext';
import { ServiceException } from './serviceException';
import { DataSyncWatcher } from "../common/dataSync/dataSyncWatcher";
export class BaseService {
    private store: Store;
    constructor() {
        DataSyncWatcher.Current.OnSyncEventListener(this.OnSync.bind(this));
    }

    private OnSync(sender: any, args: { ActionName: string; DataType: string }) {
        if (args.DataType == "Store") {
            this.GetStore(true);
        }
    }

    /**
     * 获取当前店铺配置信息 
     * 获取一次后存入内存中，下次重启后更新。
     * 
     * @protected
     * @returns 
     * @memberof BaseService
     */
    protected async GetStore(rest?: boolean) {
        if (!this.store || rest) {
            let ctx = DataContextFactory.GetDataContext();
            this.store = await ctx.Store.First();
        }

        return this.store;
    }

    /**
     * 获取当前店铺配置节点信息 
     * 
     * @protected
     * @param {string} key 配置节点名称 
     * @returns 
     * @memberof BaseService
     */
    protected async GetConfig(key: string) {
        this.store = await this.GetStore();
        if (this.store.configs instanceof Array){
            return this.store.configs.find(x => {
                return x.key === key;
            });
        }
        return undefined;
    }

    /**
     * 获取两天前的时间
     * 
     * @protected
     * @returns 
     * @memberof BaseService
     */
    protected GetTwoDayBeforeTime() {
        let today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setSeconds(0);
        let todayDate = today.getDate();
        let twoDayBefore = today.setDate(todayDate - 2);
        return twoDayBefore;
    }

    GetLockErrText(table: Table) {
        return '台桌【' + table.name + '】已被终端【' + table.lock.terminalName + '】锁定，可能正在点单或者结算。请等待【' + table.lock.terminalName + '】结束当前操作。';
    }
}